﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.ServiceModel.Syndication;
using System.Xml;
using MotaWeb.Models.Interfaces;


namespace MotaWeb.Controllers
{
    [HandleError]
    public class HomeController : MotaControllerBase
    {
        #region Constructors
        // This constructor is used by the MVC framework to instantiate the controller using
        // the default forms authentication and membership providers.
        public HomeController()
        {
        }

        // This constructor is not used by the MVC framework but is instead provided for ease
        // of unit testing this type. 
        public HomeController(IMotaWebRepository repository)
            : base(repository)
        {
        }
        #endregion


        public ActionResult Index()
        {
            LoadHomepageMessage();
            LoadHomepageSubMessage();

            LoadSlideshow();

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        #region Private Helpers
        private void LoadHomepageMessage()
        {
            string message = "Welcome to MoTA, a community of Catholics and Lutherans.";

            MotaWeb.Models.Announcement announce = null;
            announce = Repository.FindAnnouncement(DateTime.Now);

            if (announce != null)
            {
                message = announce.Message;
            }
            ViewData["Message"] = message;
        }

        private void LoadHomepageSubMessage()
        {
            var messageBuilder = new StringBuilder();
            
            const string PARSE_SEP = "<br />";
            var readingTokens = new List<string>(3);
            readingTokens.Add(ConfigurationManager.AppSettings["LectionaryFirstReadingToken"]);
            readingTokens.Add(ConfigurationManager.AppSettings["LectionaryPsalmToken"]);
            readingTokens.Add(ConfigurationManager.AppSettings["LectionarySecondReadingToken"]);
            readingTokens.Add(ConfigurationManager.AppSettings["LectionaryGospelToken"]);

            try
            {

                SyndicationFeed feed = SyndicationFeed.Load(XmlReader.Create(ConfigurationManager.AppSettings["LectionaryFeed"]));
                IEnumerable<SyndicationItem> items = feed.Items;
                foreach (var item in items)
                {
                    if (item.Summary.Text.Contains("Sunday"))
                    {
                        foreach (var token in readingTokens)
                        {
                            messageBuilder.AppendFormat("{0} {1}, ", token, ParseReadingFromSummary(item.Summary.Text, token, PARSE_SEP));
                        }

                        break;
                    }
                }
            }
            catch (Exception) { } //just swallow the exception and use the default message

            if (messageBuilder.ToString().Length == 0)
            {
                messageBuilder.Append("Every day do something that does not compute. -Wendell Berry");
            }
            ViewData["SubMessage"] = messageBuilder.ToString().Trim().TrimEnd(',');
        }

        /// <summary>
        /// This method makes some pretty big assumptions about the content of what it is parsing.
        /// It is written based off of the RSS feed from Augsburg Fortress and assumes that
        /// the target text is separated from the identifying token by some form of text
        /// in the current case a break tag.
        /// </summary>
        /// <param name="summary">Text from the RSS summary node.</param>
        /// <param name="token">The string that identifies the target reading</param>
        /// <returns>A string containing only the text of the reading verses.</returns>
        private string ParseReadingFromSummary(string summary, string token, string separator)
        {
            string reading = String.Empty;

            int tokenIndex = summary.IndexOf(token);
            int readingStart = tokenIndex + token.Length + separator.Length - 1;
            int endTokenIndex = summary.IndexOf(separator, readingStart);
            int readingLength = endTokenIndex - readingStart;

            reading = summary.Substring(readingStart, readingLength);
            return reading;

        }

        private void LoadSlideshow()
        {
            var slideshowPathSetting = ConfigurationManager.AppSettings["HomePageSlideshowPath"];
            try
            {
                string physSlideshowPath = Server.MapPath(slideshowPathSetting);
                ViewData["ImageList"] = GetImageList(physSlideshowPath);
            }
            catch (Exception)
            {
                //Swallow the error since there's nothing to do.
            }
        }

        private List<string> GetImageList(string pathName)
        {
            List<string> imageList = new List<string>();

            DirectoryInfo di = new DirectoryInfo(pathName);

            var count = di.GetFileSystemInfos().Length;

            var r = new Random();
            return (from fi in di.GetFileSystemInfos()
                         orderby r.Next(count)
                         select fi.Name).ToList();
        }

        #endregion
    }
}
